package cn.edu.zafu.bigdata.x.hjn;

import java.net.*;

public class UDPClient {
    public static void main(String[] args) {
        DatagramSocket socket = null;

        try {
            // 创建UDP套接字
            socket = new DatagramSocket();

            // 服务器的IP和端口
            String serverAddress = "localhost";  // 可以替换为同学的服务器IP
            int serverPort = 12345;

            // 发送请求数据包
            String requestMessage = "请求时间";
            byte[] sendData = requestMessage.getBytes();
            InetAddress serverInetAddress = InetAddress.getByName(serverAddress);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverInetAddress, serverPort);
            socket.send(sendPacket);  // 发送请求

            // 接收服务器返回的时间
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);  // 接收响应

            // 获取并显示服务器的时间
            String serverTime = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("从服务器接收到的时间: " + serverTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}
